package pers.qianyu.month_202101.date_20210118;

import org.junit.*;

import java.util.*;

/**
 * 166. 分数到小数
 * https://leetcode-cn.com/problems/fraction-to-recurring-decimal/
 *
 * @author mizzle rain
 * @date 2021-01-18 14:11
 */
public class FractionToDecimal {
    public String fractionToDecimal(int _a, int _b) {
        if (_b == 0) return "";
        if (_a == 0) return "0";
        int symbol = 1;
        if (_a > 0 && _b < 0 || _a < 0 && _b > 0) {
            symbol = -1;
        }
        long a = Math.abs(Long.valueOf(_a));
        long b = Math.abs(Long.valueOf(_b));
        String res = "" + (a / b);
        if (a % b == 0) {
            return symbol == -1 ? "-" + res : res;
        }
        res += ".";
        HashMap<Long, Integer> map = new HashMap<>();
        long t = a % b * 10;
        while (t != 0) {
            long mod = t % b, q = t / b;
            //System.out.println(mod + " " + q);
            if (mod == 0) {
                res = res + q;
                break;
            }
            if (map.containsKey(mod)) {
                String temp = res.substring(map.get(mod));
                if ((q + "").charAt(0) == res.charAt(map.get(mod))) {
                    res = res.substring(0, map.get(mod)) + "(" + temp + ")";
                    break;
                }
            }
            map.put(mod, res.length());
            res += q;
            t = mod * 10;
        }
        return symbol == -1 ? "-" + res : res;
    }

    @Test
    public void test1() {
        String result = new FractionToDecimal().fractionToDecimal(1, 2);
        System.out.println("result = " + result);
        Assert.assertEquals(result, "0.5");
    }

    @Test
    public void test2() {
        String result = new FractionToDecimal().fractionToDecimal(2, 3);
        System.out.println("result = " + result);
        Assert.assertEquals(result, "0.(6)");
    }

    @Test
    public void test3() {
        String result = new FractionToDecimal().fractionToDecimal(4, 333);
        System.out.println("result = " + result);
        Assert.assertEquals(result, "0.(012)");
    }

    @Test
    public void test4() {
        String result = new FractionToDecimal().fractionToDecimal(1, 6);
        System.out.println("result = " + result);
        Assert.assertEquals(result, "0.1(6)");
    }

    @Test
    public void test5() {
        String result = new FractionToDecimal().fractionToDecimal(-1, -2147483648);
        System.out.println("result = " + result);
        Assert.assertEquals(result, "0.0000000004656612873077392578125");
    }
}
